/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2024 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "i2c.h"
#include "iwdg.h"
#include "spi.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "readXYZ.h"
#include "w25qxx.h"
#include "NanoEdgeAI.h"
#include "neai_flash.h"
#include "knowledge.h"

#define EN_INT __enable_irq();     			//系统�??启全部中�??
#define DIS_INT __disable_irq();    		//系统关闭全局中断

float *data_list;
#define BUFFERSIZE 255								// 串口可接收的�????????大长�????????
#define DEVICE_ID "01"

uint8_t RECE_END_FLAG, Rx_len, bootfirst;
uint8_t ReceiveBuff[BUFFERSIZE];					// 串口接收数据数组
uint8_t CacheBuff[BUFFERSIZE];						// 数据缓冲�????????

uint8_t RECE_END_FLAG1, Rx_len1;
uint8_t ReceiveBuff1[BUFFERSIZE];					// 串口接收数据数组
uint8_t CacheBuff1[BUFFERSIZE];						// 数据缓冲�????????

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void testFlash(void) {
	uint8_t wData[0x100];   //写缓存数�????????????
	uint8_t rData[0x100];   //读缓存数�????????????
	uint8_t ID[4];          //设备ID缓存数组
	uint32_t i = 0;

	printf("\n SPI-W25Qxx Example \n\n");

	/*-Step1- 验证设备ID  ************************************************Step1*/
	BSP_W25Qx_Init();
	BSP_W25Qx_Read_ID(ID);
	//第一位厂商ID固定0xEF,第二位设备ID根据容量不同,具体为：
	//W25Q16�????????????0x14�????????????32�????????????0x15�????????????40�????????????0x12�????????????64�????????????0x16�????????????80�????????????0x13�????????????128�????????????0x17
	if ((ID[0] != 0xBA) | (ID[1] != 0x14)) {
		for (i = 0; i < 2; i++) {
			printf("0x%02X ", ID[i]);
		}
		printf("\n");
		printf("something wrong in Step1 \n");
	} else {
		printf(" W25Qxx ID is : ");
		for (i = 0; i < 2; i++) {
			printf("0x%02X ", ID[i]);
		}
		printf("\n");
	}

	if (BSP_W25Qx_Erase_Block(0) == W25Qx_OK)
		printf(" QSPI Erase Block OK!\n");
	else
		printf("something wrong in Step2\n");
	/*-Step3- 写数�???????????  ************************************************Step3*/
	for (i = 0; i < 0x100; i++) {
		wData[i] = i;
		rData[i] = 0;
	}

	if (BSP_W25Qx_Write(wData, 0x00, 0x100) == W25Qx_OK)
		printf(" QSPI Write OK!\n");
	else
		printf("something wrong in Step3\n");
	/*-Step4- 读数�???????????  ************************************************Step4*/
	if (BSP_W25Qx_Read(rData, 0x00, 0x100) == W25Qx_OK)
		printf(" QSPI Read OK!\n\n");
	else
		printf("something wrong in Step4\n");

	/*-Step5- 数据对比  ************************************************Step5*/
	if (memcmp(wData, rData, 0x100) == 0)
		printf(" W25Q64FV QuadSPI Test OK!\n");
	else
		printf(" W25Q64FV QuadSPI Test False!\n");

}

void sensorLearn(uint8_t num, uint8_t mode) {
	for (int i = 0; i < num; i++) {
		data_list = lis3dh_read_data_polling();
		neai_anomalydetection_learn(data_list);
		HAL_Delay(20);
		printf("LEARN\n");
		rs485_printf("LER\n");
		//					喂狗
		HAL_IWDG_Refresh(&hiwdg);
	}

	save_neai();
}
/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void) {

	/* USER CODE BEGIN 1 */
//	SCB->VTOR = Application_1_Addr;				// flash读取区域偏移，指向主程序存储的区�????
	//	使能全部中断
	__enable_irq();
	/* USER CODE END 1 */

	/* MCU Configuration--------------------------------------------------------*/

	/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
	HAL_Init();

	/* USER CODE BEGIN Init */

	/* USER CODE END Init */

	/* Configure the system clock */
	SystemClock_Config();

	/* USER CODE BEGIN SysInit */

	/* USER CODE END SysInit */

	/* Initialize all configured peripherals */
	MX_GPIO_Init();
	MX_DMA_Init();
	MX_I2C1_Init();
	MX_SPI1_Init();
	MX_USART1_UART_Init();
	MX_USART2_UART_Init();
	MX_IWDG_Init();
	/* USER CODE BEGIN 2 */
	__HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);		//使能串口1 IDLE中断
	__HAL_UART_ENABLE_IT(&huart2, UART_IT_IDLE);		//使能串口2 IDLE中断

	uint8_t state = 2;
	uint8_t a = 0;
	uint8_t b = 0;
	uint8_t c = 0;

	HAL_Delay(100);
	printf("HELLO L4 \n");

//	uint8_t writeflashBuff[208] = { 0 };
//
//	flash_read(0x0803f000U,writeflashBuff,208);
//	for(int i = 0 ; i< 208 ;i++){
//		printf("%2x",writeflashBuff[i]);
//	}
//	printf("\n");
	init_lis3dh();

	enum neai_state error_code = neai_anomalydetection_init();
	printf("init:%d\n", error_code);
	neai_anomalydetection_knowledge(knowledge);
	HAL_Delay(100);

	uint8_t data[1];
	BSP_W25Qx_Read(data, 0, 1);
	printf("READ:%s\n", data);
//	restore_neai();
	if (data[0] != 'D') {
		state = 2;

		printf("Knowledge\n");
		if (BSP_W25Qx_Erase_Block(0) == W25Qx_OK) {
			printf(" QSPI Erase Block OK!\n");
			BSP_W25Qx_Write("D", 0, 2);
		}
	} else {
		restore_neai();
	}
//	restore_neai();
	/* USER CODE END 2 */

	/* Infinite loop */
	/* USER CODE BEGIN WHILE */
	while (1) {
		HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, 1);
		HAL_GPIO_WritePin(LED2_GPIO_Port, LED2_Pin, 1);

		uint8_t sim = -99;
		uint8_t avg = 0;
		data_list = lis3dh_read_data_polling();

		if (state == 0 || state == 2) {
			neai_anomalydetection_detect(data_list, &sim);
			a = b;
			b = c;
			c = sim;

			avg = (a + b + c) / 3;

			printf("SIMILARITY:%d,%d\n", avg, sim);

		} else {
			for (int i = 0; i < BACK_SIZE * 3; i++) {
				printf("%4.2f,", data_list[i]);
			}
			printf("\n");
		}

//		串口读取
		if (RECE_END_FLAG == 1) {

			for (int i = 0; i < BUFFERSIZE; i++)
				CacheBuff[i] = 0;
			for (int i = 0; i < Rx_len - 1; i++) {
				CacheBuff[i] = ReceiveBuff[i];
			}
			for (int i = 0; i < BUFFERSIZE; i++)
				ReceiveBuff[i] = 0;

			printf("REC:%s\n", CacheBuff);
			HAL_UART_Receive_DMA(&huart2, (uint8_t*) ReceiveBuff,
			BUFFERSIZE);
			RECE_END_FLAG = 0; //接收标志位清�????????
			Rx_len = 0; //接收数据长度清零
			if (CacheBuff[0] == 'L') {
				uint8_t learn_num = 20;
				HAL_Delay(2000);
				printf("START LEARN\n");
				if (CacheBuff[1] == 'L') {
					neai_anomalydetection_init();
					learn_num = 80;
				}
				for (int i = 0; i < learn_num; i++) {
					data_list = lis3dh_read_data_polling();
					neai_anomalydetection_learn(data_list);
					HAL_Delay(20);
					printf("LEARN\n");
					rs485_printf("LER\n");
//					喂狗
					HAL_IWDG_Refresh(&hiwdg);
				}

				save_neai();
				rs485_printf("LERDONE\n");

				if (BSP_W25Qx_Erase_Block(0) == W25Qx_OK) {
					printf(" QSPI Erase Block OK!\n");
					BSP_W25Qx_Write("D", 0, 2);
				}
				HAL_NVIC_SystemReset();

			} else if (CacheBuff[0] == 'S') {
				state = 0;
			} else if (CacheBuff[0] == 'P') {
				state = 1;
			}

		}

//		485读取
		if (RECE_END_FLAG1 == 1) {
			for (int i = 0; i < BUFFERSIZE; i++)
				CacheBuff1[i] = 0;
			for (int i = 0; i < Rx_len1 - 1; i++) {
				CacheBuff1[i] = ReceiveBuff1[i];
			}
			for (int i = 0; i < BUFFERSIZE; i++)
				ReceiveBuff1[i] = 0;

//			printf("485REC:%s\n", CacheBuff1);
			HAL_UART_Receive_DMA(&huart1, (uint8_t*) ReceiveBuff1, BUFFERSIZE);
			RECE_END_FLAG1 = 0; //接收标志位清�????????
			Rx_len1 = 0; //接收数据长度清零
			if (CacheBuff1[0] == '#' && CacheBuff1[3] == '&'
					&& CacheBuff1[1] == DEVICE_ID[0]
					&& CacheBuff1[2] == DEVICE_ID[1]) {
				rs485_printf("%s,%d,END\n", DEVICE_ID, avg);
			}
			if (CacheBuff1[0] == 'L') {
				uint8_t learn_num = 20;
				HAL_Delay(500);
				if (CacheBuff1[1] == 'L') {
					neai_anomalydetection_init();
					learn_num = 80;
				}

				if (CacheBuff1[2] == 'L') {
					data_list = lis3dh_read_data_polling();
					neai_anomalydetection_learn(data_list);
					save_neai();
				} else {
					rs485_printf("R:REDLER\n");
					HAL_Delay(2000);
					printf("START LEARN\n");
					rs485_printf("R:STRLER\n");
					for (int i = 0; i < learn_num; i++) {
						data_list = lis3dh_read_data_polling();
						neai_anomalydetection_learn(data_list);
						printf("LEARN\n");
						rs485_printf("R:LER\n");
						//	喂狗
						HAL_IWDG_Refresh(&hiwdg);

					}

					save_neai();
					HAL_Delay(1000);
					rs485_printf("R:LERDONE\n");
					if (BSP_W25Qx_Erase_Block(0) == W25Qx_OK) {
						printf(" QSPI Erase Block OK!\n");
						BSP_W25Qx_Write("D", 0, 2);
					}
					HAL_Delay(1000);
					HAL_NVIC_SystemReset();
				}
			}

		}
		//					喂狗
		HAL_IWDG_Refresh(&hiwdg);

		HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, 0);
		HAL_GPIO_WritePin(LED2_GPIO_Port, LED2_Pin, 0);

		HAL_Delay(5);

//		HAL_Delay(100);
		/* USER CODE END WHILE */

		/* USER CODE BEGIN 3 */
	}
	/* USER CODE END 3 */
}

/**
 * @brief System Clock Configuration
 * @retval None
 */
void SystemClock_Config(void) {
	RCC_OscInitTypeDef RCC_OscInitStruct = { 0 };
	RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 };

	/** Configure the main internal regulator output voltage
	 */
	if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1)
			!= HAL_OK) {
		Error_Handler();
	}

	/** Initializes the RCC Oscillators according to the specified parameters
	 * in the RCC_OscInitTypeDef structure.
	 */
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI
			| RCC_OSCILLATORTYPE_HSE;
	RCC_OscInitStruct.HSEState = RCC_HSE_ON;
	RCC_OscInitStruct.LSIState = RCC_LSI_ON;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
	RCC_OscInitStruct.PLL.PLLM = 1;
	RCC_OscInitStruct.PLL.PLLN = 8;
	RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
	RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
	RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
	if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
		Error_Handler();
	}

	/** Initializes the CPU, AHB and APB buses clocks
	 */
	RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
			| RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
	RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
	RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
	RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
	RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

	if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) {
		Error_Handler();
	}
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
 * @brief  This function is executed in case of error occurrence.
 * @retval None
 */
void Error_Handler(void) {
	/* USER CODE BEGIN Error_Handler_Debug */
	/* User can add his own implementation to report the HAL error return state */
	__disable_irq();
	while (1) {
	}
	/* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
